import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import {useTokenStore} from '@/stores/token'
import {menu,about} from '@/web/api'
import {useNavMenuStore} from '@/stores/navMenu'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('@/views/HomeView.vue'),
    // children: [
    //   {
    //     path: '/svip',
    //     component: ()=> import('@/components/user/svip/index.vue')
    //   }
    // ]
    
  },
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/404.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes
})

router.beforeEach(async (to,from)=>{
  console.log('to',to)
  if(to.path == '/login'){
    return true
  }else{
    let routert = await initRouter()
    console.log('全部路由:',router.getRoutes())
    // 根据token的有效情况先判断是否需要登录
    const tokenStore = useTokenStore();
    if(!tokenStore.token || tokenStore.token.length == 0){
      return {
        name: 'login',
        query: {
          redirectTo: `${to.path}`,
          params: `${JSON.stringify(to.query?to.query:to.params)}`
        },
      }
    }
    return true
  }
})

router.beforeResolve (to => {
  // 判断如果用户输入的路由不存在，直接跳转到404
  if(to.matched.length == 0){
    return { name: '404',replace: true }
  }
})

/**
 * 动态初始化路由
 */
function initRouter(){
  if(useNavMenuStore().navMenus.length == 0){
    // --------------动态加载/home的子路由-------------------
    //模拟请求，拿到所有的动态路由
    let res = menu();
    //将服务端获取到的动态路由数据缓存
    useNavMenuStore().setNavMenu(res)

    /************方法1，通过取到home路由，然后加入children属性来完成嵌套路由*************** */
    //将数据转换为路由格式
    // const navData = await fn(res);
    // //将动态路由信息，加入到路由实例中
    // router.addRoute(navData)
    /**************方法2，通过文档i的router添加子路由的方法来完成*********************** */
    fn2(res)
    //-------------------------------------------------------
    // ----------------动态加载一个同级路由------------------
    const sameRouter = about()
    router.addRoute({
        path: sameRouter.path,
        name: sameRouter.name,
        component: () => import(`@/views/${sameRouter.component}.vue`)
    })
  }
}

function fn(res: any):any{
  // 只有home路径才能加子路由，做嵌套
  let homeRoutes = routes.filter(v=>v.path == '/home')[0];
  homeRoutes.children = []
  res.forEach((mitem: any) => {
    if(mitem.childs && mitem.childs.length > 0){
      mitem.childs.forEach((item: any) => {
        homeRoutes.children.push({
          path: item.path,
          name: item.name,
          component: ()=>import(`@/components/user/${item.component}/index.vue`)
        })
      });

    }else if(mitem.path){
      console.log(mitem.path)
      homeRoutes.children.push({
          path: mitem.path,
          name: mitem.name,
          component: () => import(`@/components/${mitem.component}/index.vue`)
        })
    }
  });
  return homeRoutes;
}

function fn2(res: any){
  res.forEach((mitem: any) => {
    if(mitem.childs && mitem.childs.length > 0){
      mitem.childs.forEach((item: any) => {
        router.addRoute('home',{
          path: item.path,
          name: item.name,
          component: ()=>import(`@/components/user/${item.component}/index.vue`)
        })
      });

    }else if(mitem.path){
      router.addRoute('home',{
        path: mitem.path,
        name: mitem.name,
        component: () => import(`@/components/${mitem.component}/index.vue`)
      })
    }
  });

  
}

export default router
